import type { AxiosError } from 'axios'
import axios from 'axios'
import { config } from '@/config/axios/config'
import { useUserStore } from '@/stores/user'
import { usePopupStore } from '@/stores/popup'
import { message } from 'ant-design-vue';
const service = axios.create({
	baseURL: config.baseUrl, // api 的 base_url
	timeout: config.requestTimeout, // 请求超时时间
	withCredentials: false, // 禁用 Cookie 等信息
})

service.interceptors.request.use(
	(config) => {
		const userStore = useUserStore()
		let token = null
		if(userStore.userInfo){
			token = userStore.userInfo.token
		}
		config.headers.token = token
		return config
	},
	(error) => {
		return Promise.reject(error)
	},
)

// 返回状态判断(添加响应拦截器)
service.interceptors.response.use(
	(res) => {
		if(res.data.code==2){
			const usePopup = usePopupStore()
			usePopup.setPopup('login')
			message.error(res.data.message)
			const userStore = useUserStore()
			userStore.setUser('')
		}
		return res.data
	},
	(error : AxiosError) => {
		message.error("系统错误，请稍后重试")
		return Promise.reject(error)
	},
)

export { service }